# 静态化首页
from apps.contents.models import GoodsChannel, ContentCategory
from django.template import loader
import os
from django.conf import settings


def generate_static_index_html():
    """生成静态化首页HTML文件"""

    # 创建一个字典
    categories = {}
    # 给所有一级分类排序，为了按照前端设计一样
    # channels = GoodsChannel.objects.all().order_by('group_id', 'sequence')
    # 简写
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    for channel in channels:
        # 每个频道的组id
        group_id = channel.group_id
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category
        # 取出每组一级商品分类（频道数据）信息
        categories[group_id]['channels'].append({
            'id': channel.id,  # 一级分类id
            'name': cat1.name,  # 一级分类名字，关联
            'url': channel.url
        })

        # 查找一级分类对应的二级分类,并循环遍历
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            # 使用二级分类查询关联的三级分类
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            # 添加每组中的二级和三级分类
            categories[group_id]['sub_cats'].append(cat2)

    # 广告数据
    contents = {}
    content_categroys = ContentCategory.objects.all()
    for content_cat in content_categroys:
        contents[content_cat.key] = content_cat.content_set.filter(status=True).order_by('sequence')

    # 构造上下文
    context = {
        'categories': categories,
        'contents': contents
    }

    # 根据导入的 loader 获取'index.html'模板
    template = loader.get_template('index.html')

    # 将context里的内容渲染到模板中 生成渲染过的模板
    html_str = template.render(context)

    # 拼接新的 index.html 模板将要生成的所在地地址
    file_path = os.path.join(os.path.dirname(os.path.dirname(settings.BASE_DIR)), 'front_end_pc/index.html')

    # 将渲染过的html_str转成文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_str)
